package org.luosl.webmagicx.Utils

import java.sql.{Connection, ResultSet}

/**
  * Created by luosl on 2017/12/11.
  */
object SqlUtils {

  /**
    * 数据库连接格式化
    * @param connUrl connUrl
    * @param parmas parmas
    * @param forceReplace forceReplace
    * @return
    */
  def connectFormat(connUrl:String, parmas: Map[String,String], forceReplace:Boolean = true):String = {
    val spConnUrl:String = if(forceReplace) connUrl.split("?")(0) else connUrl
    parmas.foldLeft(spConnUrl){ (url,item)=>
      if(url.contains(item._1)){
        url
      }else{
        if (url.contains("?")) {
          url + s"&${item._1}=${item._2}"
        } else {
          url + s"?${item._1}=${item._2}"
        }
      }
    }
  }

  /**
    * 格式化 sql 关键字
    * @param param param
    * @return
    */
  def paramFormat(param:String):String = {
    if(param.startsWith("`")  && param.endsWith("`")) param else s"`${param.replaceAll("`","")}`"
  }

  /**
    * 执行查询
    * @param sql sql
    * @param conn conn
    * @param op op
    * @param autoClose autoClose
    * @param params params
    */
  def executeQuery(sql:String,conn:Connection,op:ResultSet=>Unit,autoClose: Boolean,params:Any*): Unit ={
    val ps = conn.prepareStatement(sql)
    val rs = ps.executeQuery()
    try{
      if(null!=params) {
        params.foldLeft(1){(idx,param)=>
          ps.setObject(idx,param)
          idx+1
        }
      }
      while(rs.next()){
        op(rs)
      }
    }finally {
      rs.close()
      ps.close()
      if(autoClose) conn.close()
    }

  }

}
